import React from 'react';
import './onlineInquiry.less';
import { Link } from 'react-router';
import { Breadcrumb, Row, Col, Input, DatePicker, Select, Button, Table, Modal, Pagination, message, Popconfirm, TreeSelect,Popover} from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../common/config';
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const Option = Select.Option;
const config = new Config();
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');
class onlineInquiry extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [], // 数据
            phone: '', // 手机
            doctor: '', // 医生
            page: 1, // 当前页
            pagesize: 10, // 每页显示的条数
            total: 0, // 总数
            dateStr:['',''],
            date:[undefined,undefined],
            options: [],//科室
            department:undefined,//选择科室
            orderStatus:undefined,//订单状态
            payStatus:undefined,//支付状态
            visible:false,//模态框
            remark:'',//输入备注的值
            record:{},//选中的数据
            visible1:false,//确认退款
        }
        this.InputPhone = this.InputPhone.bind(this)
        this.InputDoctor = this.InputDoctor.bind(this)
        this.changeOrderState=this.changeOrderState.bind(this)
        this.changeDepartment=this.changeDepartment.bind(this)
        this.changePayStatus=this.changePayStatus.bind(this)
        this.onChangePage = this.onChangePage.bind(this)
    }

    componentDidMount() {
        this.getData();
        this.Access();

    }
    // 获取在线问诊订单列表
    getData() {
        const { page, phone,pagesize,doctor, department,orderStatus,payStatus,dateStr} = this.state
        $.ajax({
            url: `${config.onlineInquiry}/manage/queryOrders`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data: {
                pageindex:page,
                pagesize,
                phone,
                doctorName:doctor,
                deptId:department,
                orderStatus:orderStatus==2?'2,3':orderStatus,
                payStatus,
                startDate:dateStr[0],
                endDate:dateStr[1],
            },
            success: (res) => {
                // console.log('获取在线问诊订单列表', res)
                if (res.code === 200) {
                    this.setState({
                        total: res.data.count,
                        data: res.data.rows,
                    })
                }else{
                    message.error('获取列表失败，请重新操作',1);
                }
            }
        });
    }
    // 获取科室
    Access() {
        $.ajax({
            url: `${config.onlineInquiry}/getDepartments`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data: {},
            success: (res) => {
                console.log('获取科室', res)
                if (res.code === 200) {
                    this.setState({
                        options: res.data,
                    })
                }
            }
        });
    }
    //编辑备注
     handleEdit(record){
         this.setState({
             record,
             remark:record.backRemark?record.backRemark:'',
             visible:true,
         })
     }
     //保存备注
     saveBanner(){
         const{record,remark}=this.state;
         $.ajax({
             url: `${config.onlineInquiry}/manage/updateRemark`,
             type: 'POST',
             headers: {
                 'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
             },
             data: {
                 orderId:record.orderId,
                 backRemark:remark,
             },
             success: (res) => {
                 if (res.code === 200) {
                     console.log(res);
                     this.setState({
                         visible:false,
                     });
                     this.getData();
                     message.success('修改成功！',1);
                 }else{
                     message.error('更改备注失败，请重新操作',1);
                 }
             }
         });
     }
     //编辑备注
    handleRemarkChange(e){
        let value=e.target.value;
        console.log(value);
        if(value.length>=200){
            return;
        }
        this.setState({
            remark:value,
        })
    }
    //发起退款
    applyRefund(record){
        this.setState({
            record,
        })
        Modal.confirm({
            title: '退款确认',
            content: <span>确认发起&nbsp;{record.phone}&nbsp;的&nbsp;{record.amount}&nbsp;退款申请？</span>,
            onOk:() => {
                let url=`${config.onlineInquiry}/manage/applyRefund`;
                $.ajax({
                    url: url,
                    type: "POST",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                    },
                    data:{
                        orderId:record.orderId,
                    },
                    success: data => {
                        // console.log(data);
                        if (data.code === 200) {
                            message.success('申请成功！',1);
                            this.getData();
                        } else {
                            message.error(`${data.mes} 请返回重新操作`, 2);
                        }
                    }
                });
            },
            onCancel:()=>{}
        });
    }
    //退款确认
    applyRefundConfirm(record){
        this.setState({
            record,
            visible1:true,
        })
    }
    //已经转款
    isDone(){
        let {record}=this.state;
        let url=`${config.onlineInquiry}/manage/refundOrder`;
        $.ajax({
            url: url,
            type: "POST",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                orderId:record.orderId,
                isPass:1,
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    message.success('确认成功！',1);
                    this.getData();
                    this.setState({
                        visible1:false
                    })
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //拒绝
    refuse(){
        let {record}=this.state;
        let url=`${config.onlineInquiry}/manage/refundOrder`;
        $.ajax({
            url: url,
            type: "POST",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                orderId:record.orderId,
                isPass:0,
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    message.success('确认成功！',1);
                    this.getData();
                    this.setState({
                        visible1:false
                    })
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    // 表头
    getColumns() {
        return [
            {
                title: '订单号',
                width: '8%',
                dataIndex: 'orderId'
            },
            {
                title: '下单时间',
                width: '8%',
                dataIndex: 'payTime',
                render: (text, record) => {
                    if (text) {
                        return moment(text).format('YYYY-MM-DD HH:mm');
                    } else {
                        return ``
                    }

                }
            },
            {
                title: '用户电话',
                width: '7%',
                dataIndex: 'phone',
            },
            {
                title: '用户ID',
                width: '5%',
                dataIndex: 'userId',
            },
            {
                title: '医生',
                width: '7%',
                dataIndex: 'doctorName'
            },
            {
                title: '科室',
                width: '5%',
                dataIndex: 'deptName'
            },
            {
                title: '订单类型',
                width: '7%',
                dataIndex: 'productId',
                render:text=><span>{text==1?'单次':'七天'}</span>
            },
            {
                title: '金额(元)',
                width: '7%',
                dataIndex: 'amount',
                render: (record, text) => {
                    return <span style={{ color: '#ff0000' }}>{text.amount}</span>
                }
            },

            {
                title: '订单状态',
                width: '7%',
                dataIndex: 'orderStatus',
                render: (record) => {
                    let text = "";
                    switch (record) {
                        case 0:
                            text = '待支付';
                            break;
                        case 1:
                            text = '待咨询(已支付)';
                            break;
                        case 2:
                            text = '咨询中(已提问)';
                            break;
                        case 3:
                            text = '咨询中';
                            break;
                        case 4:
                            text = '已完成';
                            break;
                        case 5:
                            text = '已失效';
                            break;
                    }
                    return text;
                }
            },
            {
                title: '支付状态',
                width: '7%',
                dataIndex: 'payStatus',
                render: (record) => {
                    let text = "";
                    switch (record) {
                        case 0:
                            text = '待支付';
                            break;
                        case 1:
                            text = '已支付';
                            break;
                        case 2:
                            text = '退款中';
                            break;
                        case 3:
                            text = '已退款';
                            break;
                    }
                    return text;
                }
            },
            {
                title: '剩余时间/次数',
                width: '7%',
                dataIndex: 'validDesc'
            },
            {
                title: '备注',
                width: '7%',
                render:(text,record)=>record.backRemark?((record.backRemark.length<=6)?
                    <span >{record.backRemark}</span>:<Popover content={record.backRemark} title="备注" style={{maxWidth:'600px'}}>{record.backRemark.slice(0,6)}...</Popover>):''
            },
            {
                title: '编辑备注',
                width: '5%',
                dataIndex: 'backRemark',
                render:(text,record)=><Button  onClick={this.handleEdit.bind(this,record)}>编辑</Button>
            },
            {
                title: '操作',
                width: '5%',
                render: (text,record) => <div>{record.payStatus==1?<Button onClick={this.applyRefund.bind(this,record)}>退款</Button>:record.payStatus==2?<Button onClick={this.applyRefundConfirm.bind(this,record)}>退款处理</Button> :''}
                    </div>
            },
        ];
    }
    // 输入搜索值
    InputPhone(e) {
        this.setState({
            phone: e.target.value
        });
    }
    // 输入搜索值
    InputDoctor(e) {
        this.setState({
            doctor: e.target.value
        });
    }
    //选择科室
    changeDepartment(value) {
        console.log(value);
        this.setState({
            department: value
        });
    }
    // 选择订单状态
    changeOrderState(value) {
        this.setState({
            orderStatus: value
        })
    }
    // 选择支付状态
    changePayStatus(value) {
        this.setState({
            payStatus: value
        })
    }
    //生日禁用
    disabledDate1(val) {
        if (val) {
            return val.valueOf() > Date.now();
        } else {
            return false;
        }
    }
    //日期筛选方法
    changeDate(date, dateStr) {
        this.setState({
            dateStr,
            date,
        });
    }
    // 搜索
    search(){
        this.setState({
            page:1
        },()=>{
            this.getData();
        })
    }
    //清空
    filterOrders() {
        this.setState({
            phone: '', // 手机
            doctor: '', // 医生
            page: 1, // 当前页
            total: 0, // 总数
            dateStr:['',''],
            date:[undefined,undefined],
            department:undefined,//选择科室
            orderStatus:undefined,//订单状态
            payStatus:undefined,//支付状态
        },()=>{
            this.getData();
        })
    }
    // 切换分页
    onChangePage(page) {
        this.setState({
            page
        }, () => {
            this.getData();
        });
    }
    render() {
        const{visible,remark,visible1,record}=this.state;
        const columns = this.getColumns();
        return (
            <div className='contentBox clearfix'>
                <div className="member-content-Search">
                    <div className='breadcrumb'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>在线问诊</Breadcrumb.Item>
                            <Breadcrumb.Item>问诊订单</Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div>
                        <div className="member-content-Search" style={{ marginBottom: 20 }}>
                            <div className='addetd' style={{ zIndex: 1 }}>
                                <Input addonBefore='用户电话' placeholder="请输入用户电话" value={this.state.phone} onChange={this.InputPhone} />
                            </div>
                            <div className='addetd' style={{ zIndex: 1 }}>
                                <Input addonBefore='医生' placeholder="请输入医生姓名" value={this.state.doctor} onChange={this.InputDoctor} />
                            </div>
                            <div className='addetd addetd-a'>
                                <InputGroup compact>
                                    <Input addonBefore="科 室" />
                                    <Select value={this.state.department} placeholder='全部' onChange={this.changeDepartment.bind(this)}>
                                        {
                                            this.state.options.map((item, i) => (
                                                <Option value={`${item.id}`} key={i}>{item.name}</Option>
                                            ))
                                        }
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a addetd-kk'>
                                <InputGroup compact>
                                    <span className='chengge-a'>订单状态</span>
                                    <Select placeholder='全部' value={this.state.orderStatus} onChange={this.changeOrderState} allowClear style={{ width: 120, marginLeft: 20 }}>
                                        <Option value='0'>待支付</Option>
                                        <Option value='1'>待咨询</Option>
                                        <Option value='2'>咨询中</Option>
                                        <Option value='4'>已完成</Option>
                                        <Option value='5'>已失效</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                        </div>
                        <div className="member-content-Search" style={{ marginBottom: 20 }}>
                            <div className='addetd addetd-a addetd-kk'>
                                <InputGroup compact>
                                    <span className='chengge-a'>支付状态</span>
                                    <Select placeholder='全部' value={this.state.payStatus} onChange={this.changePayStatus} allowClear style={{ width: 120, marginLeft: 20 }}>
                                        <Option value='0'>待支付</Option>
                                        <Option value='1'>已支付</Option>
                                        <Option value='2'>退款中</Option>
                                        <Option value='3'>已退款</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd1 addetd2'>
                                <Input className='addetd-a-r' addonBefore="下单时间" />
                                <RangePicker placeholder={['请选择日期', '请选择日期']}
                                    onChange={this.changeDate.bind(this)}
                                    format='YYYY-MM-DD'
                                    value={this.state.date}
                                    disabledDate={(val) => this.disabledDate1(val)}
                                />
                            </div>
                            <Button className='ant-btn-primary' icon='search' onClick={this.search.bind(this)}>搜索</Button>
                            <Button className='ant-btn-primary' icon='sync' onClick={this.filterOrders.bind(this)}>重置</Button>
                        </div>
                    </div>
                </div>
                <div className='allgoods-table clearfix'>
                    <Table columns={columns} dataSource={this.state.data} pagination={false} bordered rowKey="orderId" />
                </div>
                <div className='goods-label-let clearfix'>
                    <div className="floor-ppagi">
                        {
                            this.state.total == 0 ?
                                <p className="floor-ppagip">
                                    共{this.state.total}条记录
              </p> :
                                <p className="floor-ppagip">
                                    当前显示
                {this.state.pagesize * (this.state.page - 1) + 1}—
                {this.state.pagesize * this.state.page < this.state.total ? this.state.pagesize * this.state.page : this.state.total}条记录，
                共{this.state.total}条记录
              </p>
                        }
                        <Pagination current={this.state.page} total={this.state.total || 1} defaultPageSize={this.state.pagesize} onChange={this.onChangePage.bind(this)} />
                    </div>
                </div>
                <Modal
                    title="编辑备注"
                    visible={visible}
                    okText="确定"
                    cancelText="取消"
                    onOk={this.saveBanner.bind(this)}
                    onCancel={()=>{this.setState({visible:false})}}
                    maskClosable={false}
                >
                    <div style={{padding:'0 30px'}}>
                        <TextArea onChange={this.handleRemarkChange.bind(this)} value={remark}/>
                    </div>
                </Modal>



                <Modal
                    title="退款确认"
                    visible={visible1}
                    onCancel={()=>{this.setState({visible1:false})}}
                    maskClosable={false}
                    footer={<div>
                        <Button onClick={this.refuse.bind(this)}>拒绝申请</Button>
                        <Button type="primary" onClick={this.isDone.bind(this)}>已转款</Button>
                    </div>}
                >
                    <div>
                        <p style={{textAlign:'center'}}>确认处理&nbsp;{record.phone}&nbsp;的&nbsp;{record.amount}&nbsp;退款申请？</p>
                    </div>
                </Modal>
            </div>
        )
    }
}

export default onlineInquiry;
